////////////////////////////////////////////////////////////////////////////////
/// CTCInterrupt.c
/// Example File to blink all LEDS attached to PORTB at 50hz using TIMER1
/// and CTC attached to an Interrupt
/// Connections:
/// Leds connected to PORTB0-7 Active Low
/// Clock set at 1mHz
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// CTC.c
/// Example File to blink all LEDS attached to PORTB at 50hz using TIMER1
/// and the CTC feature.
/// Connections:
/// Leds connected to PORTB0-7 Active Low
/// Clock set at 1mHz
////////////////////////////////////////////////////////////////////////////////



/// NO PRESCALER 
////////////////////////////////////////
/// Timer Resolution = (1 / Input Frequency)
////////////////////////////////////////
/// NO PRESCALER
////////////////////////////////////////
/// Target Count = (1 / Target Frequency) / ( 1 / Timer Clock Frequency) - 1
/// = (1 / 20) / (1 / 1000000) - 1
/// = 49999
////////////////////////////////////////
/// PRESCALER ENABLED
////////////////////////////////////////
/// Timer Resolution = (Prescale / Input Frequency)
////////////////////////////////////////
///Prescaler Value | Resolution @ 1MHz 
///              1 |  1uS 
///              8 |  8uS 
///             64 | 64uS 
///            256 | 256uS 
///           1024 | 1024uS
////////////////////////////////////////
/// Target Timer Count = (Input Frequency / Prescale) / Target Frequency - 1
////////////////////////////////////////




//Include the Header file for Input/Output Operations
#include <avr/io.h>
//Include the Header file for Interrupts
#include <avr/interrupt.h>


int main(void) { 
	//////////////////////
	/// Initialization ///
	//////////////////////
	DDRB |= 255; //Set PORTB for Output (using bit-OR statement)

	//Configure Timer Mode: CTC
	TCCR1B |= (1 << WGM12);

	//Enable CTC Interrupt
	TIMSK |= (1 << OCIE1A);
	
	//Enable global Interrupt
	sei();

	//Set Compare Value for 1Hz
	OCR1A = 15624; //Set compare value to 1Hz at 1mHz clock fOSC/64

	//Timer control register
	TCCR1B |= ((1 << CS00) | (1 << CS01)); // Set up timer for fOSC/64 prescaler
	//TCCR1B |= (1 << CS00); //Set up timer for no prescaler
	
	////////////
	/// Loop ///
	////////////
	for (;;) { //Infinite Loop
				

	}
}

//Interrupt Service Routine
ISR(TIMER1_COMPA_vect) {
	PORTB ^= 255; //Toggle the LEDs
}
